/* eslint valid-jsdoc: "off" */

/**
 * @param {Egg.EggAppInfo} appInfo app info
 */
const envFile = `.env.${process.env.NODE_ENV || 'development'}`;
require('dotenv').config({ path: envFile });

const {
  WEB_IP,
  WEB_PORT,
  MYSQL_PORT,
  MYSQL_USER,
  MYSQL_PASSWORD,
  MYSQL_DATABASE,
  JWT_SECRET,
  JWT_EXPIRES_IN,
  MYSQL_CHARSET,
} = process.env;
const defaultConfig = {
  webIP: WEB_IP,
  webPort: Number(WEB_PORT),
  mysqlPort: MYSQL_PORT,
  mysqlUser: MYSQL_USER,
  mysqlPassword: MYSQL_PASSWORD,
  mysqlDatabase: MYSQL_DATABASE,
  jwtSecret: JWT_SECRET,
  jwtExpiresIn: JWT_EXPIRES_IN,
  mysqlCharset: MYSQL_CHARSET, // 解决unicode表情插入到mysql时的报错
};

module.exports = appInfo => {
  /**
   * built-in config
   * @type {Egg.EggAppConfig}
   **/
  const config = exports = {};

  // use for cookie sign key, should change to your own and keep security
  config.keys = appInfo.name + '_1761143649553_2815';

  // add your middleware config here
  config.middleware = [];

  config.mysql = {
    client: {
      host: defaultConfig.webIP,
      port: defaultConfig.mysqlPort,
      user: defaultConfig.mysqlUser,
      password: defaultConfig.mysqlPassword,
      database: defaultConfig.mysqlDatabase,
      charset: defaultConfig.mysqlCharset,
    },
  };

  // 修改服务IP和端口
  config.cluster = {
    listen: {
      hostname: defaultConfig.webIP,
      port: defaultConfig.webPort,
    },
  };

  config.security = {
    csrf: {
      enable: false,
    },
  };

  config.cors = {
    origin: '*',
    allowMethods: 'GET,PUT,POST,DELETE,PATCH',
  };

  // token
  config.jwt = {
    secret: defaultConfig.jwtSecret, // 密钥
    expiresIn: defaultConfig.jwtExpiresIn, // token过期时间
    // tokenKey:'access-token',
    getToken({ request }) {
      return request.header['access-token'] || '';
    },
  };

  config.sequelize = {
    dialect: 'mysql',
    database: defaultConfig.mysqlDatabase,
    host: 'localhost',
    port: '3306',
    username: 'root',
    password: '123456',
    define: {
      // 取消数据库表名复数
      freezeTableName: true,

      // 自动写入时间戳 created_at和updated_at
      timestamps: true,

      // 所有驼峰命名格式化
      underscored: true,

      createdAt: 'create_time',
      updatedAt: 'update_time',

      // deletedAt: 'deleted_at',
      // paranoid: true, // 字段生成软删除时间戳 deleted_at
    },
  };

  // add your user config here
  const userConfig = {
    // myAppName: 'egg',
  };

  return {
    ...config,
    ...userConfig,
  };
};
